package com.javafactroy.kunlong.common.utils;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
@Slf4j
public class ExcelExportService {
    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setContentType("application/msexcel");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setContentType("application/msexcel");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("attachment-name", URLEncoder.encode(fileName+".xlsx", "utf-8"));

        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    public void export(HttpServletResponse response, ExcelExportDto dto) throws IOException {

        if (dto.records.size() > 0) {
            // setExcelRespProp(response,"exportxls");
            setExcelRespProp(response,dto.getFileName());

            EasyExcel.write(response.getOutputStream(), dto.records.get(0).getClass()).sheet(dto.getSheetName()).doWrite(dto.records);
        }
    }

    public void exportXls(ExcelExportDto dto) {
        if (dto.records.size() > 0) {
            EasyExcel.write(dto.getFileName(), dto.records.get(0).getClass()).sheet(dto.getSheetName()).doWrite(dto.records);
        }
    }
}
